import { isWx } from 'kuan-utils/lib/validate'
import qs from 'kuan-utils/lib/qs'
import store from '@/store'
import router from '@/router'
import authority from '@/utils/authority'

const BASE = 'https://wechat2.halobear.com/token' // 获取
export const publicPath = process.env.BASE_URL.replace(/\/$/, '')

// snsapi_base: 静默登录, 不需要用户同意, 可以拿到用户的 token, 不能拿到用户的个人信息
// snsapi_userinfo: 需要用户同意, 可以拿到用户的 token, 能拿到用户的个人信息
const SCOPE = 'snsapi_userinfo'

// 登陆地址
export function getLoginUrl(back = '') {
	const backUrl = window.location.origin + publicPath + back
	return `${BASE}?scope=${SCOPE}&back=${encodeURIComponent(backUrl)}`
}

// 主动登录
export async function login401(backUrl = router.currentRoute.fullPath) {
	const url = getLoginUrl(backUrl)
	localStorage.clear()
	await store.dispatch('logout')
	window.location.replace(url)
}

// 微信登录
export async function login(backUrl = router.currentRoute.fullPath) {
	if (!isWx) return console.warn('微信浏览器才可以登陆')
	const user = authority.get() || {}
	const isLogin = user.token
	// 已经登陆直接返回
	if (isLogin) {
		// 防止死循环
		if (isLogin === 1) {
			user.token = ''
			authority.set(user)
			console.log('登陆失败')
		}
		return true
	}
	const query = qs.parse(backUrl)
	const { wechat_code } = query
	if (wechat_code) {
		// 和上边配置防止死循环
		user.token = 1
		authority.set(user)
		// 微信登陆
		await store.dispatch('wxLogin', wechat_code)
		const [base = '', search = ''] = decodeURIComponent(backUrl).split('?')
		const filterSearch = search.replace(/(^|&)wechat_code=([^&]*)(&|$)/, '')
		const refreshUrl = `${publicPath}${base}?${filterSearch}`.replace(/\?$/, '')
		window.location.replace(refreshUrl)
	} else {
		// 重定向微信登陆
		const loginUrl = getLoginUrl(backUrl)
		window.location.replace(loginUrl)
	}
	return Promise.reject('需要登录')
}

export default login
